//
//  JDMessageViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/2/6.
//

import UIKit

class JDMessageViewController: JDBaseViewController {

    var topContainerView: UIView?
    
    /// 分类部分
    var classificationView: DraClassicHeadView?
    var classificationTitleList: [String]?// = ["全部","会议|活动","商品销售","车辆租售","房产租售","项目发起","权益转让","商务合作"]
//    400:全部、401:会议 | 活动、402:商品销售、403:车辆租售、404:房产租售、405:项目发起、406:权益转让、407:商务合作
    var classificationCodeList: [String]? // = ["400","401","402","403","404","405","406","407"]
    
    var currentSelectedType: String?
    var allNewsLabel: UILabel?
    var releaseListButton: UIButton?
    var mainTableView: UITableView?
    
    var dataSource: [JDBusinessNewsListModel?]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.removeSeparatorLine()
        self.setupConfig()
        self.setupUIElements()
        self.getBusinessNewsTypeInfo()
        
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        self.setupNavigationTitle("商务快讯")
        self.customImageLeftBarButtonItem("xlbLogo", #selector(leftButtonAction), self)
        
        self.customRightImageButton("发布",#selector(rightButtonAction))
    }
    
    @objc func leftButtonAction() {
        
    }
    
    @objc func rightButtonAction() {
        
        printLog("发布商务快讯")
        let newsFlashVC = JDNewsFlashViewController()
        self.hidesBottomBarPushViewController(newsFlashVC)
        
    }

    func setupUIElements() {
        self.topContainerView = UIView()
        self.view.addSubview(self.topContainerView!)
        self.topContainerView?.snp.makeConstraints({ make in
            make.height.equalTo(104)
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
        })
        self.topContainerView?.backgroundColor = self.commonColor
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.topContainerView!.snp.bottom)
            make.bottom.equalTo(self.view)
        })
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.register(JDQuickNewsTableViewCell.self, forCellReuseIdentifier: "myCell")
        self.mainTableView?.backgroundColor = self.commonColor
        self.mainTableView?.separatorStyle = .none
        
        self.mainTableView?.addRefreshHeader { [weak self] in
            self?.currentPage = 1
            self?.getNetData(true)
        }
        
        self.mainTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false)
        }
        
    }
    
    func setupTopView() {
        
        self.classificationView = DraClassicHeadView.init(CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width - 24, height: 44), titles: self.classificationTitleList ?? [], index: 0)
        self.topContainerView?.addSubview(self.classificationView!)
        self.classificationView?.snp.makeConstraints({ make in
            make.top.equalTo(self.topContainerView!).offset(6)
            make.left.equalTo(self.topContainerView!).offset(0)
            make.right.equalTo(self.topContainerView!).offset(0)
            make.height.equalTo(44)
        })
         
        self.classificationView?.delegate = self
        
        self.allNewsLabel = UILabel()
        self.topContainerView?.addSubview(self.allNewsLabel!)
        self.allNewsLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.topContainerView!).offset(26)
            make.top.equalTo(self.topContainerView!.snp.centerY)
            make.bottom.equalTo(self.topContainerView!)
        })
        self.allNewsLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
        self.allNewsLabel?.text = "共有 25 条快讯"

        self.releaseListButton = UIButton(type: .custom)
        self.topContainerView?.addSubview(self.releaseListButton!)
        self.releaseListButton?.snp.makeConstraints({ make in
            make.centerY.equalTo(self.allNewsLabel!)
            make.right.equalTo(self.topContainerView!).offset(-12)
            make.size.equalTo(CGSizeMake(76, 32))
        })
        self.releaseListButton?.layer.cornerRadius = 8
        self.releaseListButton?.setTitle("发布记录", for: .normal)
        self.releaseListButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.releaseListButton?.backgroundColor = .white
        self.releaseListButton?.setTitleColor(color("#333333"), for: .normal)
        self.releaseListButton?.addTarget(self, action: #selector(releaseRecordAction), for: .touchUpInside)
    }
    
    func getBusinessNewsTypeInfo() {
        
        var params = [String: Any]()
        params["showAllFlag"] = 1
        
        JDNetWorkRequest(.getBusinessNewsType(params)) { responseStr in
         
            if let businessNewTypeModels = [JDBusinessNewsTypeModel].deserialize(from: responseStr, designatedPath: "") {
                
                printLog("快讯类型:\(businessNewTypeModels)")
                
                self.classificationTitleList = businessNewTypeModels.map { model in
                    model?.name ?? ""
                }
                
                self.classificationCodeList = businessNewTypeModels.map { model in
                    model?.code ?? ""
                }
                
                self.currentSelectedType = self.classificationCodeList?.first
                
                self.setupTopView()
                self.getNetData()

            }

        } failure: { error in
            
        } error: { errorCode in
            
        }

    }
    
    override func getNetData(_ isRefresh: Bool = true) {
        
        var params = [String: Any]()
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        params["businessTypeCode"] = self.currentSelectedType
        self.showLoading()
        JDNetWorkRequest(.getBusinessNewsList(params)) { responseStr in
            print("请求成功:\(responseStr)")
            self.dismissLoading()
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                // 成功
                if let businessNewsModels = [JDBusinessNewsListModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    
                    if isRefresh {
                        // 刷新
                        self.dataSource = businessNewsModels
                    } else {
                        // 加载
                        self.dataSource?.append(contentsOf: businessNewsModels)
                    }
                    if businessNewsModels.count < 10 {
                        self.mainTableView?.reloadData()
                        self.mainTableView?.noMoreData()
                        return 
                    }
                } else {
                    self.view.toast(message: "数据异常")
                }
            } else {
                self.view.toast(message: commonModel?.msg ?? "网络异常")
            }
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
            
        } failure: { error in
            print("请求失败")
            self.view.toast(message: error.errorDescription ?? "网络异常")
            self.dismissLoading()
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        } error: { errorCode in
            print("失败\(errorCode)")
            self.view.toast(message: "网络异常")
            self.dismissLoading()
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
        }
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    @objc func releaseRecordAction() {
        printLog("查看发布列表")
        let quickNewsRecordVC = JDQuickNewsRecordViewController()
        self.hidesBottomBarPushViewController(quickNewsRecordVC)
    }
    
    @objc func loadImgeWithIndexPath(_ indexPath: IndexPath) {
           if let currentModel = self.dataSource?[indexPath.row] {
               let currentCell = self.mainTableView?.cellForRow(at: indexPath) as? JDQuickNewsTableViewCell
               currentCell?.loadImage(currentModel)
           }
       }

}

extension JDMessageViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDQuickNewsTableViewCell
        
        let currentModel = self.dataSource?[indexPath.row]
        
        cell?.businessNewsModel = currentModel
        
        self.perform(#selector(loadImgeWithIndexPath(_:)), with: indexPath, afterDelay: 0.1, inModes: [.default])
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
}

extension JDMessageViewController: DraClassicHeadViewDelegate {
    func didSelectTitleAt(_ index: Int) {
//        printLog("点击:\(self.classificationTitleList[index])->\(self.classificationCodeList[index])")
        
        self.currentSelectedType = self.classificationCodeList?[index]
        
        self.getNetData(true)
    }
}
